const pool = require('../db');
const bcrypt = require('bcryptjs');

class User {
  static async getUserByUsername(username) {
    try {
      const [rows] = await pool.execute('SELECT * FROM users WHERE username = ?', [username]);
      return rows[0] || null;
    } catch (error) {
      throw new Error(`根据用户名获取用户失败: ${error.message}`);
    }
  }

  static async createUser(userData) {
    const { username, password, role = 'user' } = userData;
    try {
      // 密码加密
      const hashedPassword = await bcrypt.hash(password, 10);
      const [result] = await pool.execute(
        'INSERT INTO users (username, password, role, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())',
        [username, hashedPassword, role]
      );
      return { id: result.insertId, username, role };
    } catch (error) {
      throw new Error(`创建用户失败: ${error.message}`);
    }
  }

  static async verifyPassword(password, hashedPassword) {
    return bcrypt.compare(password, hashedPassword);
  }

  static async getAllUsers() {
    try {
      const [rows] = await pool.execute('SELECT id, username, role, created_at, updated_at FROM users');
      return rows;
    } catch (error) {
      throw new Error(`获取用户列表失败: ${error.message}`);
    }
  }

  static async updateUserRole(id, role) {
    try {
      await pool.execute('UPDATE users SET role = ?, updated_at = NOW() WHERE id = ?', [role, id]);
      return true;
    } catch (error) {
      throw new Error(`更新用户角色失败: ${error.message}`);
    }
  }

  static async deleteUser(id) {
    try {
      await pool.execute('DELETE FROM users WHERE id = ?', [id]);
      return true;
    } catch (error) {
      throw new Error(`删除用户失败: ${error.message}`);
    }
  }
}

module.exports = User;